package com.cqs.learning.spring.cloud.producer.config.sharding;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;

/**
 * @Author lixw
 * @Date 6/4/20 12:55 AM
 */
@Slf4j
public class TransferDateShardingStrategy implements PreciseShardingAlgorithm<Timestamp> {

    private final  SimpleDateFormat format = new SimpleDateFormat("yyyy");
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Timestamp> shardingValue) {
        Timestamp value = shardingValue.getValue();
        String target = shardingValue.getLogicTableName() + "_" + format.format(value);
        for (String availableTargetName : availableTargetNames) {
            if (target.equals(availableTargetName)) {
                log.info("使用分表:{}", target);
                return target;
            }
        }
        log.warn("没有匹配到合适的表,sharding失败{}", JSON.toJSONString(shardingValue));
        return null;
    }

    public static void main(String[] args) {
        Timestamp timestamp = Timestamp.valueOf("1995-01-30 16:00:00");
        System.out.println(timestamp.getYear());
    }
}
